<?php


namespace app\admin\validate;

use think\Validate;


/**
 * 优惠券验证器
 * Class Goods
 * @package app\Goods\validate
 * @author Mr.Liu
 * @create 2021-09-16 14:23
 */
class Coupon extends Validate
{

    /**
     * 验证规则
     * @var string[]
     */
    protected $rule = [
        'id'   => 'require|number|gt:0',
        'type'                  => 'require',
        'name'                  => 'require|is_goods_unique:coupon|max:50|min:1'
    ];

    /**
     * 错误信息
     * @var string[]
     */
    protected $message = [
        'id.require'   => '参数错误',
        'id.number'    => '参数错误',
        'id.gt'        => '参数错误',
        'type.require'                  => '优惠券类型必须选择',
        'name.require'                  => '优惠券名称必须填写',
        'name.is_goods_unique'          => '优惠券名称已存在',
        'name.max'                      => '优惠券名称最多填写50个字符',
        'name.min'                      => '请填写优惠券名称'
    ];


    /**
     * 场景
     * @var \string[][]
     */
    protected $scene = [
        'create'            => ['name','type'],
        'update'            => ['name','type','id'],
    ];


    /**
     * 验证name唯一性
     * @param $value
     * @param $rule
     * @param array $data
     * @param string $field
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author Mr.Liy
     * @create 2021-09-16 13:45
     */

    public function is_goods_unique($value, $rule, array $data = [], string $field = ''): bool
    {


        $id = $data['id'] ?? 0;
        $where = [
            ['delete_time','=',0],
            ['name','=',trim($value)],
        ];
        if($id){
            $where[] = ['id','<>',$id];
        }
        if(\app\admin\model\Coupon::where($where)->value('id')){

            return false;
        }
        return true;

    }


}
